//
//  MLDPopVIew.swift
//  Sina
//
//  Created by 万世豪情 on 15/10/15.
//  Copyright © 2015年 万世豪情. All rights reserved.
//

import UIKit

protocol MLDPopViewDelegate: NSObjectProtocol {
    func popViewWillDismiss()
}

class MLDPopVIew: UIButton {
    
    weak var delegate: MLDPopViewDelegate?
    
    var imageBack: UIImageView?
    //实现构造函数
    init(customView: UIView){
    super.init(frame: CGRectMake(0, 0, SCREENW, SCREENH))
        addTarget(self, action: "converButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        setupView(customView)
        
    }
    
    private func setupView(customView: UIView){
    
        let image = UIImage(named: "popover_background")
        let imageBack = UIImageView(image: image?.stretchableImageWithLeftCapWidth(Int(image!.size.width * 0.5), topCapHeight: Int(image!.size.height * 0.5)))
        
        imageBack.size = CGSizeMake(customView.width + 10, customView.height + 22)
        
        self.addSubview(imageBack)
        self.imageBack = imageBack
        
        customView.x = 5
        customView.y = 13
        
        imageBack.addSubview(customView)
        printLog(imageBack.frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func show(targetButton:UIButton){
        
        let rect = targetButton.superview!.convertRect(targetButton.frame, toView: nil)
        
        self.imageBack?.centerX = targetButton.centerX
        self.imageBack?.y = CGRectGetMaxY(rect)
        
        //拿到window
        let window = UIApplication.sharedApplication().windows.last
        window?.addSubview(self)
        
      
    }
    
    @objc private func converButtonClick(button: UIButton){
        
        if let d = self.delegate {
            //告诉外界,我消失了
            d.popViewWillDismiss()
        }
        
        //从父控件移除
        button.removeFromSuperview()
        
    }
    
}
